package com.xjrsoft.module.base.utils;

import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiGettokenRequest;
import com.dingtalk.api.request.OapiMessageCorpconversationAsyncsendV2Request;
import com.dingtalk.api.request.OapiV2DepartmentListsubRequest;
import com.dingtalk.api.request.OapiV2UserListRequest;
import com.dingtalk.api.response.OapiGettokenResponse;
import com.dingtalk.api.response.OapiMessageCorpconversationAsyncsendV2Response;
import com.dingtalk.api.response.OapiV2DepartmentListsubResponse;
import com.dingtalk.api.response.OapiV2UserListResponse;
import com.taobao.api.ApiException;
import com.xjrsoft.module.oa.entity.XjrOaMessage;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;


@Component
public class DingtalkUtil {
    @Value("${xjrsoft.global-config.dingtalk.appKey}")
    public  String appKey;

    @Value("${xjrsoft.global-config.dingtalk.appSecret}")
    public  String appSecret;
    


    //获取token
    public  String getToken() {
        OapiGettokenResponse response = new OapiGettokenResponse();
        try {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
            OapiGettokenRequest request = new OapiGettokenRequest();
            request.setAppkey(appKey);
            request.setAppsecret(appSecret);
            request.setHttpMethod("GET");
            response = client.execute(request);
        } catch (ApiException e) {
            e.printStackTrace();
        }
       String token = response.getAccessToken();
        return token;
    }


    //根据所有部门信息
    public  List<OapiV2DepartmentListsubResponse.DeptBaseResponse> getDepartmentList(Long dept_id) throws Exception {
        String token = this.getToken();
        List<OapiV2DepartmentListsubResponse.DeptBaseResponse> deptBaseResponselist=new ArrayList<>();
        try {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/department/listsub");
            OapiV2DepartmentListsubRequest req = new OapiV2DepartmentListsubRequest();
            req.setDeptId(dept_id);
            req.setLanguage("zh_CN");
            OapiV2DepartmentListsubResponse response = client.execute(req, token);
            if(!response.isSuccess()){
                throw new Exception(response.getErrmsg());
            }
            deptBaseResponselist=response.getResult();
        } catch (Exception e) {
         throw new Exception(e.getMessage());
        }
        return deptBaseResponselist;
    }

    //获取部门的所有用户信息
    public  List<OapiV2UserListResponse.ListUserResponse> getDepartmentUser(Long dept_id) {
        String token = this.getToken();
        List<OapiV2UserListResponse.ListUserResponse> userResponselist=new ArrayList<>();
        try {
            Long cursor=0L;
            Boolean hasMore=true;
            while (hasMore) {
                DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/list");
                OapiV2UserListRequest req = new OapiV2UserListRequest();
                req.setDeptId(dept_id);
                req.setCursor(cursor);
                req.setSize(100L);
                req.setOrderField("modify_desc");
                req.setContainAccessLimit(false);
                req.setLanguage("zh_CN");
                OapiV2UserListResponse rsp = client.execute(req, token);
                userResponselist.addAll(rsp.getResult().getList());
                hasMore=rsp.getResult().getHasMore();
                cursor=rsp.getResult().getNextCursor();
            }
        } catch (ApiException e) {
            e.printStackTrace();
        }
        return userResponselist;
    }


    //发送消息给钉钉用户
    public Boolean sendMessage(XjrOaMessage xjrOaMessage,String userId) {
        String token = this.getToken();
        try {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2");
            OapiMessageCorpconversationAsyncsendV2Request request = new OapiMessageCorpconversationAsyncsendV2Request();
            request.setAgentId(839967779L);
            request.setUseridList(userId);
            request.setToAllUser(false);

            OapiMessageCorpconversationAsyncsendV2Request.Msg msg = new OapiMessageCorpconversationAsyncsendV2Request.Msg();
            msg.setMsgtype("text");
            msg.setText(new OapiMessageCorpconversationAsyncsendV2Request.Text());
            msg.getText().setContent(xjrOaMessage.getContent());
            request.setMsg(msg);
            OapiMessageCorpconversationAsyncsendV2Response rsp = client.execute(request, token);
        } catch (ApiException e) {
            e.printStackTrace();
        }
        return true;
    }
}
